package com.zhizuobiao.controller;

import com.zhizuobiao.entity.Items;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 请求参数解析
 */
@Controller
//@RequestMapping("/asdf")
public class RequestParamController {

    //    http://localhost:8080/param1?name=abc
    // value = "name",  参数名称：name，
    // required = true ,请求参数必须传入
    @RequestMapping("/param1")
    public String testParam1(@RequestParam(value = "name2", required = true) String name, Model model) {
        model.addAttribute("message", name);
        return "simple";
    }

    @RequestMapping("/param2")
    public String testParam2(@RequestParam(required = true) String email, Model model) {
        model.addAttribute("message", email);
        return "simple";
    }

    @RequestMapping("/param3")
    public String testParam3(String username, Integer age, String password, Model model) {
        model.addAttribute("message", username + " " + age + " " + password);
        return "simple";
    }

    // http://localhost:8080/param4?detail=998&price=234&name=llk
    @RequestMapping("/param4")
    public String testParam4(Items items, Model model) {
        model.addAttribute("message", items);
        return "simple";
    }


    @RequestMapping("/param5")
    public String testParam5(
            @ModelAttribute("items")
                    Items items
    ) {
        return "simple";
    }

    @RequestMapping("/param6")
    public String testParam6(Date today, Model model) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

        model.addAttribute("message", sdf.format(today));
        return "simple";
    }

    /**
     * 注册属性编辑器(字符串转换为日期)
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) throws Exception {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }


    @RequestMapping("/param6/{userid}")
    public String testParam7(@PathVariable(value = "userid") Integer id, Model model) {

        model.addAttribute("message", "id = " + id);
        return "simple";
    }
}
